package top.broncho.gank.ui.activity

import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.activity.viewModels
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.chad.library.adapter.base.BaseQuickAdapter
import com.cxz.multiplestatusview.MultipleStatusView
import com.google.android.material.appbar.AppBarLayout
import kotlinx.android.synthetic.main.activity_score.*
import org.jetbrains.anko.info
import org.jetbrains.anko.warn
import top.broncho.gank.R
import top.broncho.gank.adapter.ScoreAdapter
import top.broncho.gank.app.App
import top.broncho.gank.bean.BaseListResponseBody
import top.broncho.gank.bean.UserScoreBean
import top.broncho.gank.databinding.ActivityScoreBinding
import top.broncho.gank.widget.SpaceItemDecoration
import top.broncho.mvvm.base.BaseVMActivity


/**
 * 我的积分页面
 */
class ScoreActivity : BaseVMActivity<ActivityScoreBinding>() {

    private val viewModel by viewModels<ScoreViewModel> { viewModelFactory }
    /**
     * 每页展示的个数
     */
    private var pageSize = 20

    /**
     * RecyclerView Divider
     */
    private val recyclerViewItemDecoration by lazy {
        SpaceItemDecoration(this)
    }

    private val scoreAdapter: ScoreAdapter by lazy {
        ScoreAdapter()
    }

    /**
     * is Refresh
     */
    private var isRefresh = true

    private var contentHeight = 0F

    private var mLayoutStatusView: MultipleStatusView? = null

    override fun getLayoutId(): Int = R.layout.activity_score

    fun showLoading() {
        // swipeRefreshLayout.isRefreshing = isRefresh
    }

    fun hideLoading() {
        swipeRefreshLayout?.isRefreshing = false
        if (isRefresh) {
            scoreAdapter.setEnableLoadMore(true)
        }
    }

    fun showError(errorMsg: String) {
        mLayoutStatusView?.showError()
        if (isRefresh) {
            scoreAdapter.setEnableLoadMore(true)
        } else {
            scoreAdapter.loadMoreFail()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initView()
        viewModel.scoreData.observe({ lifecycle }) {
            swipeRefreshLayout.isRefreshing = false
            if (it.isFailure) {
                warn { "scoreData failed: ${it.exceptionOrNull()}" }
                showError(it.exceptionOrNull().toString())
                return@observe
            }
            mLayoutStatusView?.showContent()
            info { "scoreData: ${it.getOrNull()}" }
            showUserScoreList(it.getOrThrow())
        }
        if (viewModel.scoreData.value == null) {
            start()
        }
    }

    fun initView() {
        mLayoutStatusView = multiple_status_view
        toolbar.run {
            title = getString(R.string.score_detail)
            setSupportActionBar(this)
            supportActionBar?.setDisplayHomeAsUpEnabled(true)
        }

        intent.extras?.getInt("score").let {
            tv_score.text = it.toString()
        }

        swipeRefreshLayout.run {
            setOnRefreshListener(onRefreshListener)
        }
        recyclerView.run {
            layoutManager =
                LinearLayoutManager(this@ScoreActivity)
            adapter = scoreAdapter
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(recyclerViewItemDecoration)
        }
        scoreAdapter.run {
            bindToRecyclerView(recyclerView)
            setOnLoadMoreListener(onRequestLoadMoreListener, recyclerView)
            onItemClickListener = BaseQuickAdapter.OnItemClickListener { _, _, _ ->
            }
        }

        app_bar_layout.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { appBarLayout, verticalOffset ->
            contentHeight = rl_content.height.toFloat()
            val alpha = 1 - (-verticalOffset) / (contentHeight)
            rl_content.alpha = alpha
        })

    }

    override fun initColor() {
        super.initColor()
        rl_content.setBackgroundColor(mThemeColor)
    }

    fun start() {
        mLayoutStatusView?.showLoading()
        viewModel.getUserScoreList(1)
    }

    fun showUserScoreList(body: BaseListResponseBody<UserScoreBean>) {
        body.datas.let {
            scoreAdapter.run {
                if (isRefresh) {
                    replaceData(it)
                } else {
                    addData(it)
                }
                pageSize = body.size
                if (body.over) {
                    loadMoreEnd(isRefresh)
                } else {
                    loadMoreComplete()
                }
            }
        }
        if (scoreAdapter.data.isEmpty()) {
            mLayoutStatusView?.showEmpty()
        } else {
            mLayoutStatusView?.showContent()
        }
    }

    /**
     * RefreshListener
     */
    private val onRefreshListener = SwipeRefreshLayout.OnRefreshListener {
        isRefresh = true
        scoreAdapter.setEnableLoadMore(false)
        viewModel.getUserScoreList(1)
    }

    /**
     * LoadMoreListener
     */
    private val onRequestLoadMoreListener = BaseQuickAdapter.RequestLoadMoreListener {
        isRefresh = false
        swipeRefreshLayout.isRefreshing = false
        val page = scoreAdapter.data.size / pageSize + 1
        viewModel.getUserScoreList(page)
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menu?.clear()
        menuInflater.inflate(R.menu.menu_score, menu)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.action_help -> {
                val url = "https://www.wanandroid.com/blog/show/2653"
                ContentActivity.start(this@ScoreActivity, 2653, "", url)
                return true
            }
        }
        return super.onOptionsItemSelected(item)
    }

}
